package blue.txt.util;

import java.io.File;
import java.io.PrintWriter;

import blue.txt.model.FileModel;

public class FileModelUtil
{
	private FileModelUtil()
	{
	}
	
	public static void save(String dir, FileModel model)
	{
		if (model == null)
			return;
		
		File file = createFile(dir, model);
		try (PrintWriter pw = new PrintWriter(file, "UTF-8"))
		{
			pw.print("<h1>第");
			if (model.getChapter() != null)
			{
				pw.print(model.getChapter());
				pw.print("章 ");
			}
			if (model.getSection() != null)
			{
				pw.print("第");
				pw.print(model.getSection());
				pw.print("节 ");
			}
			pw.print(model.getTitle());
			pw.print("</h1>\n\n\n");
			pw.print(model.getContent());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private static File createFile(String dir, FileModel model)
	{
		File dirFile = new File(dir);
		if (!dirFile.exists())
			dirFile.mkdirs();
		
		String fileName = model.getFileName();
		if (fileName == null || fileName.isEmpty()) // 文件名为空
		{
			StringBuilder sb = new StringBuilder(32);
			
			if (model.getChapter() != null)
				sb.append(model.getChapter()).append("_");
			if (model.getSection() != null)
				sb.append(model.getSection()).append("_");
			
			sb.append(model.getTitle()).append(".txt");
			fileName = sb.toString();
		}
		return new File(dir + "/" + fileName);
	}
	
	public static String trim(String line)
	{
		return line.replaceAll("^[\\s　]*|[\\s　]*$", "");
	}
	
}
